package org.lanyu.springainovel.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.lanyu.springainovel.common.config.CustomPasswordEncoder;
import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.common.event.UserChangeEvent;
import org.lanyu.springainovel.common.mapper.UserMapper;
import org.lanyu.springainovel.common.dto.CustomUserDetails;
import org.lanyu.springainovel.common.service.UserService;
import org.lanyu.springainovel.common.service.UserCacheService;
import org.lanyu.springainovel.common.util.UserAuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CustomPasswordEncoder passwordEncoder;
    
    @Autowired
    private UserAuthUtil userAuthUtil;
    
    @Autowired
    private UserCacheService userCacheService;
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Override
    public boolean createUser(User user) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 使用用户名作为盐值加密密码，确保同一用户名的同一密码生成固定加密密码
        user.setPassword(passwordEncoder.encodeWithUsernameSalt(user.getPassword(), user.getUsername()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setEnabled(true);
        
        // 默认为普通用户
        if (user.getRole() == null) {
            user.setRole("ROLE_USER");
        }
        
        boolean result = userMapper.insert(user) > 0;
        
        // 创建成功后，发布用户创建事件
        if (result) {
            // 获取完整的用户信息（包含ID）
            User createdUser = userMapper.selectById(user.getId());
            if (createdUser != null) {
                eventPublisher.publishEvent(new UserChangeEvent(this, createdUser, UserChangeEvent.ChangeType.CREATE));
            }
        }
        
        return result;
    }

    @Override
    public boolean updateUser(User user) {
        user.setUpdateTime(new Date());
        
        // 如果有密码字段且不为空，则使用用户名作为盐值加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            // 获取用户名，如果当前用户对象中没有，则从数据库获取
            String username = user.getUsername();
            if (username == null || username.isEmpty()) {
                User existingUser = userMapper.selectById(user.getId());
                if (existingUser != null) {
                    username = existingUser.getUsername();
                }
            }
            user.setPassword(passwordEncoder.encodeWithUsernameSalt(user.getPassword(), username));
        } else {
            // 密码为空则不更新密码字段
            user.setPassword(null);
        }
        
        boolean result = userMapper.updateById(user) > 0;
        
        // 更新成功后，发布用户更新事件
        if (result) {
            // 先获取完整的用户信息
            User updatedUser = userMapper.selectById(user.getId());
            if (updatedUser != null) {
                eventPublisher.publishEvent(new UserChangeEvent(this, updatedUser, UserChangeEvent.ChangeType.UPDATE));
            }
        }
        
        return result;
    }

    @Override
    public User updateUserInfo(User user) {
        // 使用工具类获取当前登录用户
        User currentUser = userAuthUtil.getCurrentUser();
        
        // 只允许更新非敏感字段
        if (user.getNickname() != null) {
            currentUser.setNickname(user.getNickname());
        }
        if (user.getEmail() != null) {
            currentUser.setEmail(user.getEmail());
        }
        if (user.getPhone() != null) {
            currentUser.setPhone(user.getPhone());
        }
        if (user.getCustom() != null) {
            currentUser.setCustom(user.getCustom());
        }
        currentUser.setUpdateTime(new Date());
        
        // 保存更新后的用户信息
        userMapper.updateById(currentUser);
        
        // 发布用户更新事件
        eventPublisher.publishEvent(new UserChangeEvent(this, currentUser, UserChangeEvent.ChangeType.UPDATE));
        
        return currentUser;
    }

    @Override
    public boolean changePassword(String currentPassword, String newPassword) {
        // 使用工具类获取当前登录用户
        User currentUser = userAuthUtil.getCurrentUser();
        
        // 使用用户名作为盐值验证当前密码
        if (!passwordEncoder.matchesWithUsernameSalt(currentPassword, currentUser.getPassword(), currentUser.getUsername())) {
            throw new RuntimeException("当前密码不正确");
        }
        
        // 使用用户名作为盐值加密新密码并更新
        currentUser.setPassword(passwordEncoder.encodeWithUsernameSalt(newPassword, currentUser.getUsername()));
        currentUser.setUpdateTime(new Date());
        
        boolean result = userMapper.updateById(currentUser) > 0;
        
        // 更新成功后，发布用户更新事件
        if (result) {
            eventPublisher.publishEvent(new UserChangeEvent(this, currentUser, UserChangeEvent.ChangeType.UPDATE));
        }
        
        return result;
    }

    @Override
    public boolean deleteUser(Long id) {
        // 先获取用户信息用于清除缓存
        User user = userMapper.selectById(id);
        boolean result = userMapper.deleteById(id) > 0;
        
        // 删除成功后，发布用户删除事件
        if (result && user != null) {
            eventPublisher.publishEvent(new UserChangeEvent(this, user, UserChangeEvent.ChangeType.DELETE));
        }
        
        return result;
    }

    @Override
    public User getUserByUsername(String username) {
        // 使用缓存服务获取用户信息
        return userCacheService.getUserByUsername(username);
    }
    
    @Override
    public User getUserById(Long userId) {
        // 使用缓存服务获取用户信息
        return userCacheService.getUserById(userId);
    }

    @Override
    public User getCurrentUser() {
        // 使用工具类获取当前用户
        return userAuthUtil.getCurrentUser();
    }
    
    @Override
    public Long getDefaultUserId() {
        // 返回admin用户的ID（2L）
        return 2L;
    }

    @Override
    public List<User> getUserList() {
        return userMapper.selectList(null);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getUserByUsername(username);
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // 如果密码为null，尝试从数据库重新获取
        if (user.getPassword() == null) {
            user = userMapper.selectById(user.getId());
            
            if (user == null || user.getPassword() == null) {
                System.out.println("错误: 无法获取用户密码");
                throw new UsernameNotFoundException("用户密码信息不完整: " + username);
            }
        }
        
        // 返回自定义的UserDetails对象，包含用户ID和昵称
        CustomUserDetails userDetails = new CustomUserDetails(
                user.getUsername(),
                user.getPassword(),
                user.getEnabled(),
                true,  // accountNonExpired
                true,  // credentialsNonExpired
                true,  // accountNonLocked
                Collections.singletonList(new SimpleGrantedAuthority(user.getRole())),
                user.getId(),
                user.getNickname()
        );

        return userDetails;
    }
}
